package at.fhj.itm11.fotorater.model;

import javax.persistence.Entity;
import java.io.Serializable;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonManagedReference;

import java.lang.Override;
import java.util.Date;

@SuppressWarnings("serial")
@XmlRootElement
@Entity
public class Photo implements Serializable {

	@Id
	private @GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id", updatable = false, nullable = false)
	Long id = null;

	@Column
	@NotNull
	private String filepath;

	@Column
	private int likes = 0;

	@Column
	private int dislikes = 0;

	@Column
	@Size(min = 1, max = 50)
	private String name;
	
	@Column
	@NotNull
	private Date uploadDate;

	@ManyToOne
	@JsonManagedReference //to prevent circular dependencies
	@JoinColumn(referencedColumnName = "id")
	private Category category;

	public Long getId() {
		return this.id;
	}

	public void setId(final Long id) {
		this.id = id;
	}

	public Category getCategory() {
		return this.category;
	}
	
	public void setCategory(Category category) {
		this.category = category;
	}
	
	@Override
	public boolean equals(Object that) {
		if (this == that) {
			return true;
		}
		if (that == null) {
			return false;
		}
		if (getClass() != that.getClass()) {
			return false;
		}
		if (id != null) {
			return id.equals(((Photo) that).id);
		}
		return super.equals(that);
	}

	@Override
	public int hashCode() {
		if (id != null) {
			return id.hashCode();
		}
		return super.hashCode();
	}

	public String getFilepath() {
		return this.filepath;
	}

	public void setFilepath(final String filepath) {
		this.filepath = filepath;
	}

	public int getLikes() {
		return this.likes;
	}

	public void setLikes(final int likes) {
		this.likes = likes;
	}

	public int getDislikes() {
		return this.dislikes;
	}

	public void setDislikes(final int dislikes) {
		this.dislikes = dislikes;
	}

	public String getName() {
		return this.name;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public String toString() {
		String result = "";
		if (filepath != null && !filepath.trim().isEmpty())
			result += filepath;
		result += " " + likes;
		result += " " + dislikes;
		if (name != null && !name.trim().isEmpty())
			result += " " + name;
		return result;
	}
	
	/**
	 * Automatically adds a timestamp when uploading.
	 */
	@PrePersist
	protected void onUpload() {
		uploadDate = new Date();
	}
}